package com.example.other.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.other.domain.Checkitem;
import com.example.other.domain.Setmeal;
import com.example.other.domain.VO.RankVO;
import com.example.other.domain.dto.SetmealDto;
import com.example.other.domain.dto.SetmealdetailDto;
import com.example.other.service.SetmealService;
import com.example.other.mapper.SetmealMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author Limhuang
* @description 针对表【setmeal】的数据库操作Service实现
* @createDate 2024-07-03 10:15:00
*/
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal>
    implements SetmealService{

    @Autowired
    private SetmealMapper setmealMapper;

    @Override
    public List<SetmealDto> getSetmealBySex(Integer sex) {

        //1. 查询套餐详细信息列表
        List<SetmealdetailDto> setmealDetailDtos = setmealMapper.getSetmealDetailBySex(sex);

        //2. 将套餐详细信息列表按照套餐ID分组
        Map<Integer, List<SetmealdetailDto>> setmealDetailDtoMap = setmealDetailDtos.stream()
                .collect(Collectors.groupingBy(SetmealdetailDto::getId));

        //3. 遍历分组后的Map，创建SetmealDto对象并设置属性
        List<SetmealDto> setmealDtoList = new ArrayList<>();
        for (Map.Entry<Integer, List<SetmealdetailDto>> entry : setmealDetailDtoMap.entrySet()) {
            Integer setmealId = entry.getKey();
            List<SetmealdetailDto> detailDtos = entry.getValue();

            // 创建SetmealDto对象
            SetmealDto setmealDto = new SetmealDto();
            setmealDto.setId(setmealId);
            // 设置其他属性，例如name、type、price等
            setmealDto.setName(detailDtos.get(0).getName());
            setmealDto.setType(detailDtos.get(0).getType());
            setmealDto.setPrice(detailDtos.get(0).getPrice());

            // 从SetmealdetailDto中提取CheckItem信息
            List<Checkitem> checkItems = detailDtos.stream()
                    .map(detail -> {
                        Checkitem item = new Checkitem();
                        item.setCiId(detail.getCiid());
                        item.setCiname(detail.getCiname());
                        item.setCicontent(detail.getCicontent());
                        item.setMeaning(detail.getMeaning());
                        item.setRemarks(detail.getRemarks());
                        return item;
                    })
                    .collect(Collectors.toList());
            // 设置items属性
            setmealDto.setItems(checkItems);

            // 将SetmealDto对象添加到列表中
            setmealDtoList.add(setmealDto);
        }

        return setmealDtoList;
    }

    @Override
    public List<RankVO> getRank() {
        return setmealMapper.getSetmealRank();
    }
}




